import sys
from PyQt6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QApplication, QTableWidgetItem, QHeaderView, QCheckBox
from qfluentwidgets import CardWidget, PushButton, SearchLineEdit, TableWidget,setCustomStyleSheet
from database.student_db import StudentDB
from student.student_dialog import AddStudentDialog
from utils.custom_style import ADD_BUTTON_STYLE,BATCH_DELETE_BUTTON_STYLE


class StudentInterface(QWidget):
    def __init__(self):
        super().__init__()
        self.setObjectName('studentInterface')
        self.students = []
        self.setup_ui()
        self.load_data()
        self.populate_table()

    def setup_ui(self):
        layout = QVBoxLayout(self)

        #顶部按钮
        card_widget = CardWidget(self)
        buttons_layout = QHBoxLayout(card_widget)

        self.addbutton = PushButton('新增',self)
        setCustomStyleSheet(self.addbutton,ADD_BUTTON_STYLE,ADD_BUTTON_STYLE)
        self.addbutton.clicked.connect(self.add_student)

        self.searchInput = SearchLineEdit(self)
        self.searchInput.setFixedWidth(500)
        self.searchInput.setPlaceholderText("搜索学生姓名或学号...")
        self.batchDeleteButton = PushButton("批量删除",self)
        setCustomStyleSheet(self.batchDeleteButton,BATCH_DELETE_BUTTON_STYLE, BATCH_DELETE_BUTTON_STYLE)

        buttons_layout.addWidget(self.addbutton)
        buttons_layout.addWidget(self.searchInput)
        buttons_layout.addStretch(1)
        buttons_layout.addWidget(self.batchDeleteButton)

        layout.addWidget(card_widget)

        # 添加table
        self.table_widget = TableWidget(self)
        self.table_widget.setBorderRadius(8) #圆角
        self.table_widget.setBorderVisible(True) #边框
        self.table_widget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)

        #设置表头
        self.table_widget.setColumnCount(11) #设置列数
        # 设置表头文字
        self.table_widget.setHorizontalHeaderLabels(["","学生ID","姓名","学号","性别","班级","语文","数学"
            ,"英语","总分","操作"])
        layout.addWidget(self.table_widget)

        self.setStyleSheet("StudentInterface {background-color:white;}")
        self.resize(1280,760)

    def load_data(self):
        """self.students = [
            {"student_id": 1,"student_name": "张三","student_number": "2035546","gender": 1,"class_name": "23软件1班","chinese_score": 98,"math_score": 87,"english_score": 64,"total_score": 354},
            {"student_id": 2, "student_name": "月月", "student_number": "2035546", "gender": 2,"class_name": "23软件1班", "chinese_score": 98, "math_score": 87, "english_score": 64, "total_score": 354},
        ]"""
        with StudentDB() as db:
            self.students = db.fetch_students()

    def populate_table(self):
        self.table_widget.setRowCount(len(self.students))
        for row,student_info in enumerate(self.students):
            self.setup_table_row(row,student_info)

    def setup_table_row(self, row, student_info):
        checkbox = QCheckBox()
        self.table_widget.setCellWidget(row, 0, checkbox)
        for col, key in enumerate(['student_id', 'student_name','student_number','gender', 'class_name', 'chinese_score', 'math_score', 'english_score','total_score']):
            value = student_info.get(key, '')
            # 设置性别
            if key == 'gender':
                value = '男' if value == 1 else '女' if value == 2 else '未知'
            # 单元格赋值
            item = QTableWidgetItem(str(value))
            self.table_widget.setItem(row, col +1, item)

    def add_student(self):
        """添加学生信息"""
        dialog = AddStudentDialog(self)
        if dialog.exec():
            print("操作成功")
        else:
            print("用户取消操作")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = StudentInterface()
    window.show()
    sys.exit(app.exec())